#include "monster.h"

#include "libtcod.hpp"

#include <string>

#include "character.h"

#include "maps.h"
#include "messageController.h"

using namespace fortress;

monster::monster() : messages(messageController::getInstance()), currentMap(0)
{

}

monster::~monster()
{

}

void monster::insert(character * addMonster)
{
	for(std::list<storedMonster>::iterator it = controlled.begin(); it != controlled.end(); it++)
	{
		if ((*it).first==addMonster)
		{
			throw std::string("This monster already exists on the AI list.");
			return;
		}
	}
	addMonster->setAI(this);
	storedMonster newMonster;
	newMonster.first=addMonster;
	newMonster.second=(addMonster->isOnMap(currentMap));
	controlled.push_back(newMonster);
}

void monster::remove(character const * oldMonster)
{
	for(std::list<storedMonster>::iterator it = controlled.begin(); it != controlled.end(); it++)
	{
		if ((*it).first==oldMonster)
		{
			(*it).first->setAI(0);
			controlled.erase(it);
			return;
		}
	}
	throw std::string("Monster not on AI priority list.");
}
/*
void monster::dummy()
{
	std::ofstream output("qwer.txt");
	boost::archive::binary_oarchive oa(output);
	oa << *this;
}
*/
void monster::takeTurn(character * sameMap)
{
	if (currentMap==0)
		throw std::string("No map set for AI");

	TCODRandom * rng = TCODRandom::getInstance();
	for(std::list<storedMonster>::iterator it = controlled.begin(); it != controlled.end(); it++)
	{
		if (!(*it).first->isOnMap(sameMap) && !(*it).first->isDead())
			(*it).first->move(rng->getInt(-1,1), rng->getInt(-1,1));
	}
	for (std::list<character*>::iterator it = currentMap->monsterList->begin(); it!=currentMap->monsterList->end(); it++)
	{
		if ((*it)->isControlledByAI() && !(*it)->isDead())
			(*it)->move(rng->getInt(-1,1), rng->getInt(-1, 1));
	}
}

template<class Archive>
void monster::serialize(Archive & ar, const unsigned int version)
{
	ar & controlled;
}
template void monster::serialize<boost::archive::binary_oarchive>(boost::archive::binary_oarchive & ar, const unsigned int version);
template void monster::serialize<boost::archive::text_oarchive>(boost::archive::text_oarchive & ar, const unsigned int version);
template void monster::serialize<boost::archive::text_iarchive>(boost::archive::text_iarchive & ar, const unsigned int version);
